package com.yao.spring.cloud.weather.service.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yao.spring.cloud.weather.service.WeatherDataService;
import com.yao.spring.cloud.weather.vo.WeatherResponse;

/**
 * WeatherDataService 实现
 * 
 * @Description: TODO(用一句话描述该文件做什么)
 * @author yaoym
 * @date 2018年3月20日 下午3:07:55
 * @version V1.0
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

	private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public WeatherResponse getDataByCityID(String cityID) {

		String uri = WEATHER_URI + "citykey=" + cityID;

		WeatherResponse resp = this.dogetWeather(uri);

		return resp;
	}

	@Override
	public WeatherResponse getDataByCityName(String cityName) {

		String uri = WEATHER_URI + "city=" + cityName;
		WeatherResponse resp = this.dogetWeather(uri);
		return resp;
	}

	private WeatherResponse dogetWeather(String uri) {

		ResponseEntity<String> respStr = restTemplate.getForEntity(uri, String.class);

		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse resp = null;
		try {
			resp = mapper.readValue(respStr.getBody(), WeatherResponse.class);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return resp;
	}
}
